<template>
	<l-page class="page-card" :page.sync="queryParams.pageNum" :page-size.sync="queryParams.pageSize" :total="total" @getList="getList">
		<el-form ref="queryForm" slot="header" :inline="true" :model="queryParams" label-width="90px">
			<el-form-item label="商品ID:" prop="id">
				<el-input v-model.trim="queryParams.id" clearable placeholder="请输入商品ID" maxlength="6" show-word-limit />
			</el-form-item>
			<el-form-item label="商品名称:" prop="name">
				<el-input v-model.trim="queryParams.name" clearable placeholder="请输入商品名称" maxlength="11" show-word-limit />
			</el-form-item>
			<el-form-item label="商品分类:" prop="category">
				<el-cascader ref="category" :props="props" placeholder="请选择商品分类" @change="change"></el-cascader>
			</el-form-item>
			<el-form-item label="上架状态:" prop="isOnSale">
				<el-select v-model="queryParams.isOnSale" placeholder="上架状态">
					<el-option :value="null" label="全部"></el-option>
					<el-option :value="1" label="上架"></el-option>
					<el-option :value="0" label="下架"></el-option>
				</el-select>
			</el-form-item>
			<start-end-time ref="child" :get-time="getTime" title="创建时间:"></start-end-time>
		</el-form>

		<template slot="options">
			<div class="flex items-center justify-between w-full">
				<div class="flex items-center">
					<l-search @search="handleQuery" @refresh="resetQuery" />
					<!--					<el-button icon="el-icon-plus" type="primary" @click="handleAdd">发布商品</el-button>-->
				</div>
				<!--				<div class="btn-box flex justify-between items-center">-->
				<!--					<div class="right" @click="goAudit">-->
				<!--						待审核商品 <span style="color: #f14a46">{{ auditGoods }}</span-->
				<!--						><span style="color: #6373ee">（点击此处进行审核）</span>-->
				<!--					</div>-->
				<!--				</div>-->
			</div>
		</template>

		<template slot="card">
			<el-tabs v-model="tabActive" class="tabs">
				<el-tab-pane v-for="(item, index) in tabData" :key="index" :label="item.label + `（${tabStatistics[item.key]}）`" :name="item.key"></el-tab-pane>
			</el-tabs>
		</template>
		<el-table ref="goodsDown" v-loading="loading" :data="goodsList" stripe @selection-change="handleSelectionChange" @sort-change="handleSortChange">
			<el-table-column :formatter="emptyToString" align="center" label="序号" type="index" width="55" />
			<el-table-column :formatter="emptyToString" align="center" label="商品ID" prop="id"></el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品名称" prop="goods_name" show-overflow-tooltip width="150px">
				<template slot-scope="scope">
					<div class="goods-name-style">
						{{ scope.row.name }}
					</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="商品图片">
				<template slot-scope="scope">
					<el-image :preview-src-list="[scope.row.picUrl]" :src="scope.row.picUrl" style="width: 50px; height: 50px"></el-image>
				</template>
			</el-table-column>

			<!--			<el-table-column :formatter="emptyToString" align="center" label="供应商名称" min-width="110" prop="userName" />-->
			<el-table-column :formatter="emptyToString" :show-overflow-tooltip="true" align="center" label="商品类型" min-width="156">
				<template slot-scope="scope">
					{{ scope.row.oneLevel + ' > ' + scope.row.twoLevel }}
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToNumber" align="center" prop="retailPrice" label="商品价格" sortable min-width="156">
				<template slot-scope="scope">
					<div>{{ scope.row.retailPrice || 0 }}</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToNumber" align="center" label="批发价格" min-width="156" prop="supplyPrice" sortable />
			<!--			<el-table-column :formatter="emptyToNumber" align="center" label="抵扣金额" min-width="156" prop="deductPrice" sortable />-->
			<el-table-column :formatter="emptyToNumber" align="center" label="销量" prop="commoditySales" />

			<el-table-column :formatter="emptyToString" align="center" label="上架状态" prop="isOnSale">
				<template slot-scope="scope">
					<el-switch
						v-model="scope.row.isOnSale"
						:active-value="1"
						:inactive-value="0"
						active-text="上架"
						class="switch"
						inactive-text="下架"
						@change="handleUpdateStatus(scope.row, 'isOnSale')"
					></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="更新时间" min-width="200" prop="createTime">
				<template slot-scope="scope">
					<div class="w-full flex flex-col items-center">
						<span>{{ dayjs(scope.row.createTime).format('YYYY-MM-DD') }}</span>
						<span>{{ dayjs(scope.row.createTime).format('HH:mm:ss') }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" :width="tableAction" align="left" fixed="right" header-align="center" label="操作">
				<template slot-scope="scope">
					<div class="table-action flex justify-center">
<!--												<el-button  type="primary" @click="handleUpdate(scope.row)">详情 </el-button>-->
						<!--						<el-button v-hasPermi="['mall:goods:remove']" type="danger" @click="handleDelete(scope.row)">删除 </el-button>-->
					</div>
				</template>
			</el-table-column>
		</el-table>
	</l-page>
</template>

<script>
import { addGoods, delGoods, exportGoods, getAuditGoods, listGoods, updateGoods, updateGoodsList } from '@/api/mall/goods';
import { listChild, listParent } from '@/api/mall/category';
import { isArray } from '@/utils/validate';
import tableMixins from '@/mixins/table';

export default {
	name: 'GoodsList',
	mixins: [tableMixins],
	beforeRouteEnter(to, from, next) {
		next((vm) => {
			if (from.path === '/goods/create') {
				vm.getList();
			}
		});
	},
	data() {
		return {
			tabActive: 'totalCount',
			tabData: [
				{
					label: '全部',
					name: null,
					key: 'totalCount',
				},
				{
					label: '上架',
					name: 1,
					key: 'waitCount',
				},
				{
					label: '下架',
					name: 0,
					key: 'refuseCount',
				},
			],
			tabStatistics: {
				auditAmount: 0,
				auditCount: 0,
				refuseAmount: 0,
				refuseCount: 0,
				totalCount: 0,
				waitAmount: 0,
				waitCount: 0,
			},
			tableAction: 50,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			//待审核商品
			auditGoods: 0,
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 商品基本信息表格数据
			goodsList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 搜索参数
			queryParams: {
				pageNum: this.$route.query.pageNum || 1,
				pageSize: 10,
				userName: null,
				id: null,
				goodsSn: null,
				name: null,
				category: null,
				brandId: null,
				gallery: null,
				brief: null,
				brand: null,
				isOnSale: null,
				sortStr: null,
				sortDesc: null,
				burst: null,
				isHot: null,
				sortOrder: null,
				unit: null,
				counterPrice: null,
				retailPrice: null,
				goodsType: 1,
				orderType: 1,
				storeType: null,
				chain: 1,
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				goodsSn: [{ required: true, message: '商品编号不能为空', trigger: 'blur' }],
				name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
			},
			checkboxGroup: [],
			// 商品信息
			// 商品类型
			// 商品分类
			// 商品价格
			// 供应商价格
			// 销量
			// 商品库存
			// 商品状态
			// 创建时间
			cities: [
				{ value: true, label: '商品信息', id: 'a0' },
				{ value: true, label: '商品类型', id: 'a1' },
				{ value: true, label: '商品分类', id: 'a2' },
				{ value: true, label: '商品价格', id: 'a3' },
				{ value: true, label: '销量', id: 'a4' },
				{ value: true, label: '商品库存', id: 'a5' },
				{ value: true, label: '商品状态', id: 'a6' },
				{ value: true, label: '创建时间', id: 'a7' },
				{ value: true, label: '操作', id: 'a8' },
			],
			cobj: {
				a0: true,
				a1: true,
				a2: true,
				a3: true,
				a4: true,
				a5: true,
				a6: true,
				a7: true,
				a8: true,
			},
			goodsDetail: '',
			detailDialogVisible: false,
			goodsTypeList: [],
			props: {
				lazy: true,
				lazyLoad(node, resolve) {
					const { level, value } = node;
					if (level === 0) {
						listParent().then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: false,
							}));
							resolve(nodes);
						});
					} else {
						listChild(value).then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: true,
							}));
							resolve(nodes);
						});
					}
				},
			},
		};
	},
	watch: {
		tabActive() {
			const item = this.tabData.find((item) => item.key === this.tabActive);
			this.queryParams.isOnSale = item.name;
			this.handleQuery();
		},
	},
	created() {
		console.log(this.queryParams.pageNum);
		this.getList();
		this.getAuditList();
		this.getDicts('mall_goods_type').then((response) => {
			this.goodsTypeList = response.data;
		});
		this.getCategory();
		this.getStatisticsV2();
	},
	methods: {
		getStatisticsV2() {
			this.$request.get('/mall/goods/queryCount').then((res) => {
				this.tabStatistics = {
					totalCount: res.data[0],
					waitCount: res.data[1],
					refuseCount: res.data[2],
				};
			});
		},
		getCategory() {
			this.$request.post('/api/category/listOne').then((res) => {
				this.categoryList = res.data;
			});
		},
		getAuditList() {
			getAuditGoods({
				current: 1,
				size: 10,
			}).then((res) => {
				this.auditGoods = res.data.total;
			});
		},
		goAudit() {
			this.$router.push({
				path: '/goods/audit',
			});
		},
		handleUpdateTop(row) {
			updateGoods({ id: row.id, top: row.top })
				.then(() => {
					this.$message.success(row.top ? '置顶成功' : '取消置顶成功');
					this.getList();
				})
				.catch(() => {
					row.status = !row.status;
				});
		},
		reSortOrderReduce(id) {
			this.$request.post('/mall/goods/reSortOrderReduce', { id }).then(() => {
				this.getList();
			});
		},
		reSortOrderPlus(id) {
			this.$request.post('/mall/goods/reSortOrderPlus', { id }).then(() => {
				this.getList();
			});
		},
		change(value) {
			this.queryParams.category = value[value.length - 1];
		},
		/** 搜索商品基本信息列表 */
		editInventory(id) {
			this.$prompt('请输入需要编辑的库存数量', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /(^[0-9]\d*$)/,
				inputErrorMessage: '请输入正整数(包含0)',
			})
				.then(({ value }) => {
					updateGoods({ id, inventory: Number(value) }).then(() => {
						this.$message.success('编辑成功!');
						this.getList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '取消输入',
					});
				});
		},
		editPrice(id) {
			this.$prompt('请输入需要编辑的价格', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /(^\d+$)|(^\d+\.\d+$)/,
				inputErrorMessage: '请输入正数',
			})
				.then(({ value }) => {
					updateGoods({ id, retailPrice: Number(value) }).then(() => {
						this.$message.success('编辑成功!');
						this.getList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '取消输入',
					});
				});
		},
		getList() {
			this.loading = true;
			listGoods(this.queryParams)
				.then((response) => {
					this.goodsList = response.data.records;
					this.total = response.data.total;
					this.setActionWidth();
				})
				.finally(() => {
					this.loading = false;
				});
		},
		handleCurrentChange(newPage) {
			this.queryParams.pageNum = newPage.page;
			this.queryParams.pageSize = newPage.limit;
			this.getList();
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				goodsSn: null,
				name: null,
				categoryId: null,
				brandId: null,
				gallery: null,
				keywords: null,
				brief: null,
				isOnSale: null,
				sortOrder: null,
				picUrl: null,
				shareUrl: null,
				isNew: null,
				isHot: null,
				unit: null,
				counterPrice: null,
				retailPrice: null,
				detail: null,
				delFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
			};
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		getTime(startTime, endTime) {
			this.queryParams.startTime = startTime;
			this.queryParams.endTime = endTime;
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.$refs.category.$refs.panel.clearCheckedNodes();
			this.$refs.child.resetTime();
			this.resetForm('queryForm');
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.$router.push('/goods/create');
		},
		/** 编辑按钮操作 */
		handleUpdate(row) {
			this.reset();
			console.log(this.queryParams.pageNum);
			const id = row.id || this.ids;
			// this.$router.push('/goods/chainDetails?id=' + id + '&pageNum=' + this.queryParams.pageNum);
      this.$router.push(`/goods/details?id=${row.id}&type=audit`);
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					if (this.form.id != null) {
						updateGoods(this.form).then(() => {
							this.msgSuccess('编辑成功');
							this.open = false;
							this.getList();
						});
					} else {
						addGoods(this.form).then(() => {
							this.msgSuccess('新增成功');
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			let ids = row.id || this.ids;
			if (!isArray(ids)) {
				ids = [ids];
			}

			this.$confirm('是否删除商品ID为"' + ids + '"的商品?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return delGoods(ids);
				})
				.then(() => {
					this.getList();
					this.msgSuccess('删除成功');
				});
		},
		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有商品基本信息数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return exportGoods(queryParams);
				})
				.then((response) => {
					this.download(response.msg);
				});
		},
		showDetail(detail) {
			this.goodsDetail = detail;
			this.detailDialogVisible = true;
		},
		handleUpdateStatus(row, key) {
			updateGoods(row)
				.then(() => {
					this.$message.success('更新成功');
					this.getList();
				})
				.catch(() => {
					row[key] = !row[key];
				});
		},
		handleCategoryChange(value) {
			this.queryParams.categoryId = value[value.length - 1];
		},
		batchPutAway() {
			let currentSelect = this.$refs.goodsDown.selection;
			let itemArr = [];

			for (let i = 0; i < currentSelect.length; i++) {
				itemArr.push(currentSelect[i]);
				currentSelect[i].isOnSale = 1;
				console.log(currentSelect[i]);
			}
			updateGoodsList(itemArr).then(() => {
				this.$message.success('上架成功!');
				this.getGoodsList();
			});
		},
		batchSoldOut(row) {
			let currentSelect = this.$refs.goodsDown.selection;
			let itemArr = [];

			for (let i = 0; i < currentSelect.length; i++) {
				itemArr.push(currentSelect[i]);
				currentSelect[i].isOnSale = 2;
				console.log(currentSelect[i]);
			}
			updateGoodsList(itemArr).then((res) => {
				this.$message.success('下架成功!');
				this.getGoodsList();
			});
		},
	},
};
</script>
<style>
.minibtn_padding.el-button--primary {
	background-color: #1d2eb8;
	border-color: #1d2eb8;
}

.minibtn_padding.el-button--danger {
	background-color: #1a2483;
	border-color: #1a2483;
}
</style>
<style lang="scss" scoped>
.btn-box {
	display: flex;
	justify-content: space-between;
	align-items: center;

	.right {
		height: 36px;
		background: #eff0ff;
		border: 1px solid #c9d0ff;
		opacity: 1;
		border-radius: 5px;
		font-size: 12px;
		padding-left: 16px;
		box-sizing: border-box;
		line-height: 36px;
		cursor: pointer;
	}
}
</style>
